package com.steel.yfmall.cloud.assistant.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.steel.yfmall.cloud.assistant.BackstageConstants;
import com.steel.yfmall.cloud.assistant.api.stock.ZgSendCompanyInfoAPI;
import com.steel.yfmall.cloud.assistant.bean.AssistantConstants;
import com.steel.yfmall.cloud.assistant.bean.param.APIParamUserCompanyBean;
import com.steel.yfmall.cloud.assistant.common.CommonPublicInfoService;
import com.steel.yfmall.cloud.assistant.dto.para.user.ParaSendSmsInfoBean;
import com.steel.yfmall.cloud.assistant.dto.zg.ZgCallWsdlAPIBaseDTO;
import com.steel.yfmall.cloud.assistant.po.user.SteelCompanyCustomerCategory;
import com.steel.yfmall.cloud.assistant.po.user.SteelCompanyCustomerCategoryExample;
import com.steel.yfmall.cloud.assistant.user.SmsInfoBeanService;
import com.steel.yfmall.cloud.assistant.utils.kd.EasLoginUtil;
import com.steel.yfmall.cloud.assistant.utils.zg.ZgCallServiceUtils;
import com.steel.yfmall.cloud.assistant.utils.zg.ZgMethodBeanUtil;
import com.steel.yfmall.cloud.common.bean.param.APIParamMallConfigBean;
import com.steel.yfmall.cloud.common.bean.result.APIResultMallConfigBean;
import com.steel.yfmall.cloud.components.utils.base.APIMsgBean;
import com.steel.yfmall.cloud.components.utils.base.ResponseCode;

import com.steel.yfmall.cloud.components.utils.utils.ResultCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: ZgSendCompanyInfoAPIImpl
 * @author: liuzhijun
 * @date: 2020-12-23 20:32
 **/
@Service
@Slf4j
public class ZgSendCompanyInfoAPIImpl implements ZgSendCompanyInfoAPI {

    /**
     * 产品实例，固定值
     **/
    public static final String SLNNAME = "eas";

    /**
     * 金蝶EAS系统数据中心代码
     **/
    public static final String DBCODE = "jy02";

    /**
     * 语言：L2，简体中文；L3，繁体中文；固定值
     **/
    public static final String LANGUAGE = "L2";

    /**
     * 数据库类型：0，SqlServer；1，Oracle
     **/
    public static final int DBTYPE = 1;

    @Override
    public APIMsgBean<String> sendCompanyInfo(APIParamUserCompanyBean beanInfo) {
        APIMsgBean<String> apiMsgBean = new APIMsgBean<String>();
        String secondCateCode = beanInfo.getResponseSteelUserCompanyExtendInfo().getSecondCateCode();
        String firstCateCode = beanInfo.getResponseSteelUserCompanyExtendInfo().getFirstCateCode();

        apiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean("审核失败,没有获取到对应的企业编码信息"));
        try {
            //参数信息拼接
            JSONObject main = new JSONObject();
            main.put("Fname", beanInfo.getCompanyName());
            main.put("FtaxRegisterNo", beanInfo.getResponseSteelUserCompanyExtendInfo().getCompanyIdNumber());
            //获取企业分类编码
            if (StringUtils.isBlank(secondCateCode) || StringUtils.isBlank(firstCateCode)) {
                apiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean("企业分类信息为空"));
                return apiMsgBean;
            }

            SteelCompanyCustomerCategoryExample example = new SteelCompanyCustomerCategoryExample();
            example.createCriteria().andParentCateCodeEqualTo(firstCateCode).andCateCodeEqualTo(secondCateCode);
            List<SteelCompanyCustomerCategory> areaList = steelCompanyCustomerCategoryMapper.selectByExample(example);
            if (areaList == null || CollectionUtils.isEmpty(areaList)) {
                apiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean("企业分类信息不存在"));
                return apiMsgBean;
            }
            if (StringUtils.isBlank(areaList.get(0).getCateCode())) {
                apiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean("企业二级分类编码信息不存在"));
                return apiMsgBean;
            }
            //传入金蝶系统省市区id
            main.put("customerNum", areaList.get(0).getCateCode());
            //填充方法信息
            ZgCallWsdlAPIBaseDTO zgCallWsdlAPIBaseDTO = new ZgCallWsdlAPIBaseDTO();
            //请求地址
            zgCallWsdlAPIBaseDTO.setUrl(ZG_SEND_USER_COMPANY_URL);
            //方法名
            zgCallWsdlAPIBaseDTO.setInterfaceName(ZgMethodBeanUtil.EMS_TO_ADDCUSTOMER);
            //参数名称
            zgCallWsdlAPIBaseDTO.setParameterType(ZgMethodBeanUtil.ORMRPC);


            //填充方法信息
            ZgCallWsdlAPIBaseDTO wsdlUtilBean = new ZgCallWsdlAPIBaseDTO();
            //请求地址
            wsdlUtilBean.setUrl(JYJT_ZGSYSTEM_EASLOGIN_URL);
            //方法名
            wsdlUtilBean.setInterfaceName("login");
            //调用登录EAS接口
            boolean dataBean = EasLoginUtil.easLogin(new Object[]{userName, password, SLNNAME, DBCODE, LANGUAGE, DBTYPE}, wsdlUtilBean);

            apiMsgBean = zgCallServiceUtils.commonCallZgSoApi(main, zgCallWsdlAPIBaseDTO);

            String result = apiMsgBean.getData();

            //解析接口返回参数
            JSONObject returnMap = JSON.parseObject(result);
            String status = returnMap.get(ZgMethodBeanUtil.STATE).toString();
            //是否返回成功
            if (!"1".equals(status)) {
                apiMsgBean.setData(String.valueOf(returnMap.get("msg")));
                apiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean("审核失败,推送金蝶系统失败"));
                return apiMsgBean;
            }
            beanInfo.setCompanyCode(String.valueOf(returnMap.get("number").toString()));
            apiMsgBean.setData(beanInfo.getCompanyCode());
            apiMsgBean.setSoaStateBean(ResponseCode.buildEnumSuccessSOAStateBean());
            //审核通过后发送短信
            //是否开启同步中冠处获取余额值  开启将查询crm  同步本地   关闭将获取本商城余额值信息
            APIParamMallConfigBean apiParamMallConfigBean = new APIParamMallConfigBean();
            apiParamMallConfigBean.setConfigKey(BackstageConstants.PAY_CHECK_SMS_NOTIFICATION);
            apiParamMallConfigBean.setStatus(BackstageConstants.STATUS_OK);
            apiParamMallConfigBean.setSiteCode(AssistantConstants.DEFALUT_SITECODE);
            APIMsgBean<APIResultMallConfigBean> apiMsg = commonPublicInfoService.gyfmallConfigInfoByPara(apiParamMallConfigBean);
            if (apiMsg != null && apiMsg.getData() != null && apiMsg.getSoaStateBean() != null && apiMsg.getSoaStateBean().getCode() == ResultCodeConstants.SUCCESS
                    && StringUtils.equalsIgnoreCase(apiMsg.getData().getConfigValue(), "true")) {
                String phone = beanInfo.getPhone();
                String companyName = beanInfo.getCompanyName();
                if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(companyName)) {
                    ParaSendSmsInfoBean apiParaSendSmsInfoBean = new ParaSendSmsInfoBean();
                    apiParaSendSmsInfoBean.setPhone(phone);
                    apiParaSendSmsInfoBean.setContent(companyName);
                    apiParaSendSmsInfoBean.setUserName(BackstageConstants.NAME);
                    apiParaSendSmsInfoBean.setNickName(BackstageConstants.NAME);
                    apiParaSendSmsInfoBean.setSourceType(BackstageConstants.TYEP);
                    apiParaSendSmsInfoBean.setSendType(BackstageConstants.TYEP);
                    apiParaSendSmsInfoBean.setTemplateCode(BackstageConstants.APPROVED);
                    smsInfoBeanService.sendSms(apiParaSendSmsInfoBean);
                }
            }
            log.info("数据库短信配置:"+JSONObject.toJSON(apiMsg));
        } catch (Exception e) {
            log.error("推送金蝶系统获取企业编码信息异常" + JSONObject.toJSONString(beanInfo), e);
        }
        return apiMsgBean;
    }

    @Value("${jyjt_zgSystem_sendUserCompany_url}")
    private String ZG_SEND_USER_COMPANY_URL;

    @Value("${jyjt_zgSystem_easLogin_url}")
    private String JYJT_ZGSYSTEM_EASLOGIN_URL;

    @Value("${userName}")
    private String userName;

    @Value("${password}")
    private String password;

    @Resource
    private com.steel.yfmall.cloud.assistant.user.mapper.SteelCompanyCustomerCategoryMapper steelCompanyCustomerCategoryMapper;

    @Resource
    private ZgCallServiceUtils zgCallServiceUtils;
    /**
     * 短信服务
     */
    @Resource
    private SmsInfoBeanService smsInfoBeanService;

    /**
     * 开关查询
     */
    @Resource
    private CommonPublicInfoService commonPublicInfoService;
}
